using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using NLP_Library;
using System.Data.SqlClient;
using System.Data;
using MySql.Data.MySqlClient;


public class AskingQuestionsScreen : MonoBehaviour {
	
	
	private NLP_Manager m_pNLPmanager = null;            // NLPComponent to be created on either a different Library or the current one.
    //private CQuestionManager m_pQuestionManager = null;
    private string sOriginalQuestion;
	private string[] m_questions;
	
    string question = "";
    string answer = "";
    //This is a stupid way of doing it but I can't think of a better way -Cameron
    struct ErrorList
    {
        public string[] user;
        public string[] caseID;
        public string[] timestamp;
        public string[] question;
        public string[] nlpQuestion;
        public string[] answer;
    }
    ErrorList mismatches;
    bool[] toggles;
    int[] finalToggles;
    int counter;
    public Rect windowRect = new Rect(600, 300, 650, 300);
    Vector2 scrollPosition = new Vector2(0,0);
    System.DateTime startTime;
    int timeLimit;
    int points;
	public GUITexture topBar;
	public GUIStyle questionnaireStyle;
	public GUIStyle reviewOfSystemStyle;
	public GUIStyle casePhotosStyle;
	public GUIStyle loggedInStyle;
	public GUIStyle timeRemainingStyle;
	public GUIStyle logOffStyle;
	public GUIStyle finalChoicesStyle;
	public GUIStyle qImageStyle;
	bool b_questionnaire = false;
	bool b_reviewOfSystem = false;
	bool b_casePhotos = false;
	//Rect chatBoxRect = new Rect(0, Screen.height-185, 485, 185);
	Rect biggerChatBoxRect = new Rect(Screen.width/2-489, Screen.height-378, 978, 378);
	string userName = "";
	Vector2 chatScrollPosition = new Vector2(0,0);
	public GUIStyle chatBoxWindowStyle;
	public GUIStyle chatBoxChatAreaStyle;
	public GUIStyle chatBoxQuestionStyle;
	public GUISkin chatBoxSkin;
	System.DateTime currentTime;
	bool showChat;
	Vector2 qScrollPosition = new Vector2(0,0);
	public Texture2D qTexture;
	public Texture2D rosTexture;
	public Texture2D leftBTexture;
	public Texture2D rightBTexture;
	public Texture2D casePBGTexture;
	Rect qRect = new Rect(Screen.width/2-512, 30, 1024, Screen.height);
	int caseCounter;
	Texture2D[] casePhotos;
	Rect casePRect = new Rect(Screen.width/2-512, 30, 1024, Screen.height);
	//Rect casePRectBG = new Rect(Screen.width/2-277, 30, 555, 275);
	public GUITexture casePBG;
	int totalPoints = 0;
	bool focus = true;
	public GUIStyle blankStyle;
	public Texture logo;
	public GUIStyle rightChatBoxStyle;
	
	struct ChatBoxText{
		public string text;
		public bool question;
	}
	
	ArrayList chatBoxText = new ArrayList();
	
	
	string message = "";
	MySqlDataReader reader;
	MySqlConnection connection;
	MySqlCommand command;
	string query;
	List<string> caseQuestions = new List<string>();
	NLP_Manager NLP = new NLP_Manager();
	string[] NLPQuestions;
	System.DateTime finishTime;
	List<string> casePhotoURLs = new List<string>();
	
	//Basic code for downloading images from internet
	/*
	public GUITexture t; //Make sure to set this so something either in code or in the editor
	string url = "https://docs.google.com/open?id=0B_4gVL4hW8OZdmRocUMyMnlpNEE";
	
	void Start(){
		StartCoroutine(Pic());
	}
	
	IEnumerator Pic() {
        WWW www = new WWW(url);
        yield return www;
        t.texture = www.texture;
    }
    
    
    
	*/
	
	
    void Start()
    {
		try
        {
            connection = new MySqlConnection(Configuration.MySQLConnectionString);
            connection.Open();
			
			using (connection)
			{
				query = "SELECT q.text FROM Question q, CaseQuestionSet cqs WHERE cqs.Case_case_id='" + User.SelectedCase +"' AND q.QuestionSet_question_set_id=cqs.QuestionSet_question_set_id";
				command = new MySqlCommand(query, connection);
		        reader = command.ExecuteReader();
	            while (reader.Read())
	            {
					caseQuestions.Add(reader["text"].ToString());
				}
			}
			
			connection = new MySqlConnection(Configuration.MySQLConnectionString);
            connection.Open();
			
			using (connection)
			{
				query = "SELECT c.time_minutes_allowed FROM VP_OFP.Case c WHERE c.case_id=" + User.SelectedCase;
				command = new MySqlCommand(query, connection);
		        reader = command.ExecuteReader();
				reader.Read();
				if(reader.HasRows){
					User.TimeAllowed = (int)reader["time_minutes_allowed"];
				}
			}
			
			connection = new MySqlConnection(Configuration.MySQLConnectionString);
            connection.Open();
			
			using (connection)
			{
				query = "SELECT url FROM VP_OFP.PatientExamPictures WHERE Case_case_id=" + User.SelectedCase;
				command = new MySqlCommand(query, connection);
		        reader = command.ExecuteReader();
				reader.Read();
				if(reader.HasRows){
					casePhotoURLs.Add(reader["url"].ToString());
				}
			}
			
		}
		catch (Exception ex)
        {
			message = ex.Message;
			return;
        }
		
		NLPQuestions = new string[caseQuestions.Count];
		
		for(int i=0; i<caseQuestions.Count; i++){
			NLPQuestions[i] = caseQuestions[i];
		}
		
		NLP.SetupInitialPat(Configuration.WordNetDictionnaryPath);
		//NLP.CreateNewQuestionArray(NLPQuestions);
		
		finishTime = System.DateTime.Now.AddMinutes(User.TimeAllowed);
		casePhotos = new Texture2D[casePhotoURLs.Count];
		for(int i=0; i<casePhotoURLs.Count; i++){
			StartCoroutine(GetCasePhotos(i));
		}
		
    }
	
	IEnumerator GetCasePhotos(int id) {
		WWW www = new WWW(casePhotoURLs[id]);
    	yield return www;
    	casePhotos[id] = www.texture;
	}
	

    void OnGUI()
    {
		int width = Screen.width / 2;
		int height = Screen.height / 2;
		GUI.Button(new Rect(0, 50, 160, 45), logo, blankStyle);
		topBar.pixelInset = new Rect(-512, height - 30, 1024, 30);
		GUI.skin = chatBoxSkin;
		if(b_questionnaire = GUI.Toggle(new Rect(width - 330, 0, 119, 30), b_questionnaire, "", questionnaireStyle)){
			b_reviewOfSystem = false;
			b_casePhotos = false;
		}
		if(b_reviewOfSystem = GUI.Toggle(new Rect(width - 210, 0, 149, 30), b_reviewOfSystem, "", reviewOfSystemStyle)){
			b_questionnaire = false;
			b_casePhotos = false;
		}
		if(b_casePhotos = GUI.Toggle(new Rect(width - 60, 0, 108, 30), b_casePhotos, "", casePhotosStyle)){
			b_questionnaire = false;
			b_reviewOfSystem = false;
		}
		GUI.Label(new Rect(width + 100, 0, 167, 34), User.UserName + " is logged in", loggedInStyle);
		System.TimeSpan temp = finishTime-System.DateTime.Now;
		string secs = temp.Seconds.ToString();
		if(temp.Seconds < 10){
			secs = "0" + temp.Seconds.ToString();
		}
		GUI.Label(new Rect(width + 275, 0, 167, 34), "Time Remaining: " + temp.Minutes.ToString() + ":" + secs, loggedInStyle);
	
		if(Event.current.type == EventType.KeyDown){
			showChat = true;
			question = "";
		}
        
		if(b_questionnaire || b_reviewOfSystem || b_casePhotos){
			focus = false;
		}
		else{
			focus = true;
		}
        
		if(b_questionnaire){
			qRect = GUI.Window(2, qRect, QWindow, "", timeRemainingStyle);
		}
		if(b_reviewOfSystem){
			qRect = GUI.Window(3, qRect, ROSWindow, "", timeRemainingStyle);
		}
		if(b_casePhotos){
			casePBG.enabled = true;
			casePRect = GUI.Window(4, casePRect, CaseWindow, "", timeRemainingStyle);
		}
		else{
			casePBG.enabled = false;
			if (GUI.Button(new Rect(Screen.width/2+300, 50, 200, 55), "", finalChoicesStyle))
	        {
	            Application.LoadLevel(3);
	        }
			if(showChat){
				biggerChatBoxRect = GUI.Window(1, biggerChatBoxRect, ChatBox, User.UserName+"\tAccumulated Score: "+totalPoints+"/100");
				GUI.BringWindowToBack(1);
				if(focus){
					GUI.FocusWindow(1);
				}
			}
		}
		
		GUI.skin = null;
        
    }
	
	void ChatBox(int id){
		chatScrollPosition = GUILayout.BeginScrollView(chatScrollPosition);
        foreach(ChatBoxText i in chatBoxText){
			if(i.question == true){
				GUILayout.Label(i.text);
			}
			else{
				GUILayout.Label(i.text, rightChatBoxStyle);
			}
		}
		GUILayout.EndScrollView();
		GUILayout.BeginHorizontal();
		GUI.SetNextControlName("qField");
		question = GUILayout.TextField(question, 256);
		if(question == " "){
			question = "";
		}
		GUILayout.EndHorizontal();
		if(Event.current.type == EventType.KeyDown && Event.current.character == '\n'){
			if(question != ""){
				ChatBoxText q;
				ChatBoxText a;
				q.text = userName + ": " + question + "\n";
				q.question = true;
		        AskQuestion(question, out answer, out points);
				totalPoints += points;
				question = "";
				if(points != 0){
					a.text = "Patient: " + answer + "\t(" + points + "/5)\n";
				}
				else{
					a.text = "Patient: " + answer + "\n";
				}
				a.question = false;
				chatBoxText.Add(q);
				chatBoxText.Add(a);
				chatScrollPosition = new Vector2(0, Mathf.Infinity);
			}
        }
	}
	
	void QWindow(int id){
		qScrollPosition = GUILayout.BeginScrollView(qScrollPosition);
		GUILayout.Button(qTexture, qImageStyle);
		GUILayout.EndScrollView();
	}
	
	void ROSWindow(int id){
		qScrollPosition = GUILayout.BeginScrollView(qScrollPosition);
		GUILayout.Button(rosTexture, qImageStyle);
		GUILayout.EndScrollView();
	}
	
	void CaseWindow(int id){
		if(GUI.Button(new Rect(240, 120, 35, 35), leftBTexture, qImageStyle)){
			if(caseCounter-1 >= 0){
				caseCounter--;
			}
			else{
				caseCounter = casePhotos.Length-1;
			}
		}
		GUI.Button(new Rect(casePRect.width/2-175, 30, 350, 225), casePhotos[caseCounter], qImageStyle);
		if(GUI.Button(new Rect(740, 120, 35, 35), rightBTexture, qImageStyle)){
			if(caseCounter + 1 <= casePhotos.Length - 1){
				caseCounter++;
			}
			else{
				caseCounter = 0;
			}
		}
		
	}
	
	public void GetMismatches(out string[] user, out string[] caseID, out string[] timestamp, out string[] question, out string[] nlpQuestion, out string[] answer)
        {
            DBGetMismatches(out user, out caseID, out timestamp, out question, out nlpQuestion, out answer);
        }
	
	public bool AskQuestion(string question, out string answer, out int p)
        {
            string sQuestionCode;
            int points = 0;
            if (question == "")
            {
                answer = "Invalid question";
                p = 0;
                return false;
            }
			
            // 1. Process the question with the NLP\
            NLPE_MAN_RRORCODE coderesult = m_pNLPmanager.ProcessQuestion(question, out sOriginalQuestion);

            // question was asked
            InternalComponents.m_iQuestionsAsked++;

            if (coderesult == NLPE_MAN_RRORCODE.NLP_OK)
            {
                // 2. Finds the best answer using the DB
                RequestSpecificAnswer(sOriginalQuestion, out answer);
                RequestPoints(sOriginalQuestion, out points);
                RequestQuetionID(sOriginalQuestion, out sQuestionCode);

                // 2.1 Save the amount of points
                InternalComponents.m_iTotalScore += points;
                InternalComponents.m_lQuestionsAsked.Add(sQuestionCode);

                // 3. Report the answer to the question manager
                //m_pQuestionManager.informOfQuestionAnswered(points);
            }
            else
            {
                answer = "Sorry I don't understand your question.";
                InternalComponents.m_iQuestionsFailed++;
            }

            // 4. Change state if the question manager indicates so
		/*
            if (m_pQuestionManager.GetChangeState())
                ForceStateChange();
                */

            p = points;
            return true;
        }
	
	public static bool SaveStagePosition(string userID, int currentPosition)
        {
            // stores currentPosition as the current stage (asking questions, final decision, etc) the user is on
			// Stages in our program right now 
			/*
			 * 1. Login Screen
			 * 2. Case Selection
			 * 3. Asking Questions
			 * 4. Final Choice 
			 * 
			 * */
			
            bool result = false;

            try {
                //Actaul SQL Query
                SqlConnection con;
                con = new SqlConnection();
                //this has to change based on the config file that will be implemented ultimately
                con.ConnectionString = "server=128.125.243.240;Initial Catalog=AVP_RCA;User ID=sa;Password=2ndL1fe";
                //con.ConnectionString = ConfigurationManager.AppSettings["AVP_RCAConnectionString"].ToString();

                con.Open();
                using (con) {

                    string strQuery = "UPDATE Sessions " +
                                      "SET currentStage = @currentPosition " +
                                      "WHERE idUsers = @userID "; 
                                          
					
                    SqlCommand cmd = new SqlCommand(strQuery, con);

                    // Add external parameters to the command
                    SqlParameter param = new SqlParameter("@userID", SqlDbType.Int); // 1. Set the tipe of parameter to use
                    param.Value = Convert.ToInt32(userID);							 // 2. Set the value of the parameter to use
                    cmd.Parameters.Add(param);										 // 3. Add the parameter to the command parameters

                    SqlParameter param2 = new SqlParameter("@currentPosition", SqlDbType.Int); // 1. Set the tipe of parameter to use
                    param2.Value = currentPosition;							 // 2. Set the value of the parameter to use
                    cmd.Parameters.Add(param2);										 // 3. Add the parameter to the command parameters


                    int iRowAffected = cmd.ExecuteNonQuery();
                    if (iRowAffected > 0) {
                        result = true;
                    }
                    con.Close();
                }
            }

            catch (Exception ex) {
                Console.WriteLine(ex.Message);
                result = false;
            }
            return result;
        }
	
	public static bool RequestQuestionArray(string availableCaseId, out string[] questions, out int size) {
            bool result = false;
            questions = null;
            size = -1;

            // query to access data from DB & get all the relavant questions
            try {
                ArrayList arrQn = new ArrayList();
                //Actaul SQL Query
                SqlConnection con;
                con = new SqlConnection();
                //this has to change based on the config file that will be implemented ultimately
                con.ConnectionString = "server=128.125.243.240;Initial Catalog=AVP_RCA;User ID=sa;Password=2ndL1fe";
                //con.ConnectionString = ConfigurationManager.AppSettings["AVP_RCAConnectionString"].ToString();

                con.Open();
                using (con) {
                    /*
                    * Needed Query in SQL
                    * -------------------
                    * SELECT caseName
                    * FROM AvailableCases
                    * WHERE idAvailableCases in
                    *                         ( SELECT idAvailableCases 
                    *                           FROM   Sessions
                    *                           WHERE idUsers = @userID AND
                    *                                 idSessions = @sessionID
                    *                          )        
                    */


                    string strQuery = "SELECT question " +
                                    "FROM TemplateOfAnswers " +
                                    "WHERE idTypesOfCases = " + availableCaseId;

                    SqlCommand cmd = new SqlCommand(strQuery, con);
					
                    // Add external parameters to the command
                    SqlParameter param = new SqlParameter("@availableCaseId", SqlDbType.Int); // 1. Set the tipe of parameter to use
                    param.Value = Convert.ToInt32(availableCaseId);							 // 2. Set the value of the parameter to use
                    cmd.Parameters.Add(param);										        // 3. Add the parameter to the command parameters

                    SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    if (rdr.HasRows) {
                        while (rdr.Read()) {
                            arrQn.Add(rdr["question"]);
                        }
                    }

                    con.Close();
                }
                questions = new string[arrQn.Count];
                for (int cnt = 0; cnt < arrQn.Count; cnt++) {
                    questions[cnt] = arrQn[cnt].ToString();
                }
                size = arrQn.Count;
            }

            catch (Exception ex) {
                Console.WriteLine(ex.Message);
                result = false;
            }

            return result;
        }
	
	public static bool DBGetTimeLimit(out int timeLimit, string caseID)
        {
            //Sets timeLimit to the number of minutes that the user has to complete the case. Each case has a time limit. If infinite amount of time leave as zero
            timeLimit = 0;			
			bool result = false;
			try{
				int idCase = Convert.ToInt32(caseID);
				//Actaul SQL Query
                SqlConnection con;
                con = new SqlConnection();
                con.ConnectionString = "server=128.125.243.240;Initial Catalog=AVP_RCA;User ID=sa;Password=2ndL1fe";
                //con.ConnectionString = ConfigurationManager.AppSettings["AVP_RCAConnectionString"].ToString();

                con.Open();
                using (con)
                {
                    string strQuery = "SELECT timeLimit "+
                                      "FROM AvailableCases "+
                                      "WHERE idAvailableCases='" + idCase + "'";

                    SqlCommand cmd = new SqlCommand(strQuery, con);
                    SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    
                    if (rdr.HasRows)
                    {
						if(rdr.Read()){
							timeLimit = Convert.ToInt32(rdr[0].ToString());					
						}
						
                    }
                }
                con.Close();
			}
			catch(Exception ex){
				Console.WriteLine(ex.ToString());
				result = false;
			}
			
            return result;
        }
	
	public static bool DBDeleteMismatches(int[] mismatches) {
            //Delete the mismatches from the db. Mismatches is their position in the list
            DataTable dtMismatchTable = new DataTable("MismatchLog");

            bool result = false;

            try {

                //Actaul SQL Query
                SqlConnection con;
                con = new SqlConnection();
                //this has to change based on the config file that will be implemented ultimately
                con.ConnectionString = "server=128.125.243.240;Initial Catalog=AVP_RCA;User ID=sa;Password=2ndL1fe";
                //con.ConnectionString = ConfigurationManager.AppSettings["AVP_RCAConnectionString"].ToString();

                con.Open();
                using (con) {
                    string strQuery = "SELECT * FROM MismatchLog";

                    SqlCommand cmd = new SqlCommand(strQuery, con);
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    //this will query the database and return the result to the datatable
                    da.Fill(dtMismatchTable);
                    foreach (int i in mismatches) {
                        dtMismatchTable.Rows[i].Delete();
                    }
                    int rowsAffected  = da.Update(dtMismatchTable);
                    if (mismatches.Length != 0 && rowsAffected > 0)
                        result = true;
                    else
                        result = false;
                    da.Dispose();
                }
                con.Close();
            }
            catch (Exception ex) {
                Console.WriteLine(ex.Message);
                result = false;
            }
            return result;
        }
	
	public static bool RequestSpecificAnswer(string relatedQuestion, out string relatedAnswer) {
            // function returning true or false based on whether the answer array was filled with
            // the appropriate answer for the related question
            return getAnswerByQuestion(relatedQuestion, out relatedAnswer);
        }

    public static bool RequestPoints(string relatedQuestion, out int relatedPoints) {
            // function returning true or false based on whether the points counter was filled appropriately
            return getPointsByQuestion(relatedQuestion, out relatedPoints);
        }

    public static bool RequestQuetionID(string relatedQuestion, out string relatedID) {
            return getQuestionIdByQuestionDescription(relatedQuestion, out relatedID);
        }
	
	private static bool getAnswerByQuestion(string inQn, out string outAnswer) {

            outAnswer = String.Empty;
            bool res = false;
            string sqlCmd = "SELECT answer FROM TemplateOfAnswers WHERE question = @inQn";
            //this has to change based on the config file that will be implemented ultimately
            string ConnectionString = "server=128.125.243.240;Initial Catalog=AVP_RCA;User ID=sa;Password=2ndL1fe";


            try {
                SqlConnection con;
                con = new SqlConnection();
                con.ConnectionString = ConnectionString;
                con.Open();
                using (con) {
                    SqlCommand cmd = new SqlCommand(sqlCmd, con);
                    // Add external parameters to the command
                    SqlParameter param = new SqlParameter("@inQn", SqlDbType.VarChar, 1024); // 1. Set the tipe of parameter to use
                    param.Value = inQn;							 					// 2. Set the value of the parameter to use
                    cmd.Parameters.Add(param);										// 3. Add the parameter to the command parameters

                    SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

                    if (rdr.HasRows) {
                        while (rdr.Read()) {
                            outAnswer = rdr["answer"].ToString();
                        }
                    }
                    con.Close();

                }
            }

            catch (Exception ex) {
                Console.WriteLine(ex.Message);
                res = false;
            }
            return res;
        }
	
	private static bool getPointsByQuestion(string inQn, out int outPoints) {

            outPoints = -1;
            bool res = false;
            string sqlCmd = "SELECT pointsValue FROM TemplateOfAnswers WHERE question = @inQn";
            //this has to change based on the config file that will be implemented ultimately
            string ConnectionString = "server=128.125.243.240;Initial Catalog=AVP_RCA;User ID=sa;Password=2ndL1fe";


            try {
                SqlConnection con;
                con = new SqlConnection();
                con.ConnectionString = ConnectionString;
                con.Open();
                using (con) {
                    SqlCommand cmd = new SqlCommand(sqlCmd, con);
                    // Add external parameters to the command
                    SqlParameter param = new SqlParameter("@inQn", SqlDbType.VarChar, 1024);     // 1. Set the tipe of parameter to use
                    param.Value = inQn;							                        // 2. Set the value of the parameter to use
                    cmd.Parameters.Add(param);	                                        // 3. Add the parameter to the command parameters

                    SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    if (rdr.HasRows) {
                        while (rdr.Read()) {
                            outPoints = Convert.ToInt16(rdr["pointsValue"].ToString());
                            res = true;
                            rdr.Close();
                            con.Close();
                            break;
                        }
                    }
                }
            }

            catch (Exception ex) {
                Console.WriteLine(ex.Message);
                res = false;
            }
            return res;
        }
	
	private static bool getQuestionIdByQuestionDescription(string relatedQuestion, out string relatedID) {
            bool result = false;
            relatedID = String.Empty;

            try {

                //Actaul SQL Query
                SqlConnection con;
                con = new SqlConnection();
                //this has to change based on the config file that will be implemented ultimately
                con.ConnectionString = "server=128.125.243.240;Initial Catalog=AVP_RCA;User ID=sa;Password=2ndL1fe";
                //con.ConnectionString = ConfigurationManager.AppSettings["AVP_RCAConnectionString"].ToString();

                con.Open();
                using (con) {
                    string strQuery = "SELECT idTemplateOfAnswers " +
                                      "FROM TemplateOfAnswers " +
                                      "WHERE question = @relatedQuestion ";

                    SqlCommand cmd = new SqlCommand(strQuery, con);
                    SqlParameter param = new SqlParameter("@relatedQuestion", SqlDbType.VarChar, 1024);     // 1. Set the tipe of parameter to use
                    param.Value = relatedQuestion;							                        // 2. Set the value of the parameter to use
                    cmd.Parameters.Add(param);	                                        // 3. Add the parameter to the command parameters

                    SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    if (rdr.HasRows) {
                        while (rdr.Read()) {
                            relatedID = rdr["idTemplateOfAnswers"].ToString();
                            result = true;
                        }
                    }
                }

                con.Close();
            }

            catch (Exception ex) {
                Console.WriteLine(ex.Message);
                result = false;
            }
            return result;
        }
	
	public void SetNLPComponent(NLP_Manager newNLP)            // NLPComponent to be created on either a different Library or the current one.
    {
        // 1) save the nlp that is going to be used
        m_pNLPmanager = newNLP;
        // we finish here as the nlp is initialized on the init function
    }
	
	public static bool DBGetMismatches(out string[] user, out string[] caseID, out string[] timestamp, out string[] question, out string[] nlpQuestion, out string[] answer) {
            //Return the mismatch list
            user = null;
            caseID = null;
            timestamp = null;
            question = null;
            nlpQuestion = null;
            answer = null;
            DataTable dtMismatchTable = new DataTable("MismatchLog");

            bool result = false;

            try {

                //Actaul SQL Query
                SqlConnection con;
                con = new SqlConnection();
                //this has to change based on the config file that will be implemented ultimately
                con.ConnectionString = "server=128.125.243.240;Initial Catalog=AVP_RCA;User ID=sa;Password=2ndL1fe";
                //con.ConnectionString = ConfigurationManager.AppSettings["AVP_RCAConnectionString"].ToString();

                con.Open();
                using (con) {
                    string strQuery = "SELECT * FROM MismatchLog";

                    SqlCommand cmd = new SqlCommand(strQuery, con);
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    //this will query the database and return the result to the datatable
                    da.Fill(dtMismatchTable);
                    da.Dispose();
                }
                con.Close();
                DataRowCollection drc = dtMismatchTable.Rows;
                int capacity = drc.Count;
                user = new string[capacity];
                caseID = new string[capacity];
                timestamp = new string[capacity];
                question = new string[capacity];
                nlpQuestion = new string[capacity];
                answer = new string[capacity];
                int count = 0;
                foreach (DataRow dr in drc) {
                    user[count] = dr[1].ToString();
                    caseID[count] = dr[2].ToString();
                    question[count] = dr[3].ToString();
                    answer[count] = dr[4].ToString();
                    timestamp[count] = dr[5].ToString();
                    nlpQuestion[count] = dr[6].ToString();
                    count++;
                }
				if(count!=0)
					result = true;

            }

            catch (Exception ex) {
                Console.WriteLine(ex.Message);
                result = false;
            }
            return result;
        }

	
}
